package com.uflower.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.uflower.common.to.es.SkuEsModel;
import com.uflower.search.constant.Constant;
import com.uflower.search.service.EsProductService;
import com.uflower.search.vo.SearchParams;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
@Service
@Slf4j
public class EsProductServiceImpl implements EsProductService {
    @Autowired
    RestHighLevelClient client;


    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) {
        BulkRequest bulkRequest = new BulkRequest();
        for(SkuEsModel model: skuEsModels){
            IndexRequest indexRequest = new IndexRequest(Constant.PRODUCT_INDEX);
            indexRequest.id(model.getSkuId().toString());
            indexRequest.source(JSON.toJSONString(model), XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse responses = null;
        try {
           responses = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        }catch (Exception e){
            e.printStackTrace();
        }
        if(responses.hasFailures()){
            log.error("sku上架出错");
            BulkItemResponse[] items = responses.getItems();
            Arrays.stream(items).forEach(item->{
                System.out.println(item);
            });
            return false;
        }
            return true;
    }
}
